/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package create_view_modify;

import cse308.entities.Studentoutcome;
import cse308.GUIUtilityClass;
import cse308.UserSessionBean;
import cse308.entities.Degreeprogram;
import cse308.entities.Peo;
import cse308.entities.Targetattainmentlevel;
import cse308.entities.Targetdirectassessment;
import cse308.entities.Targetsurveyassessment;
import cse308.entities.Users;
import cse308.helper_classes.GeneralTest;
import cse308.helper_classes.PEOClass;
import cse308.helper_classes.StudentOutcomeClass;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Aaron
 */
@ManagedBean(name = "studentOutcomesBean")
@SessionScoped
public class StudentOutcomesBean implements Serializable {

    @ManagedProperty(value = "#{userSessionBean}")
    private UserSessionBean userSessionBean;
    @ManagedProperty(value = "#{gUIUtilityClass}")
    private GUIUtilityClass utilities;
    private final static Logger LOG = Logger.getLogger(GUIUtilityClass.class.getName());
    private String title;
    private String identifier;
    private int seqNum;
    private String shortName;
    private String Description;
    private List<StudentOutcomeClass> studentOutcomes;

    /**
     * Creates a new instance of StudentOutcomesBean
     */
    public StudentOutcomesBean() {
    }

    public GUIUtilityClass getUtilities() {
        return utilities;
    }

    public void setUtilities(GUIUtilityClass utilities) {
        this.utilities = utilities;
    }

    public String viewStudentOutcomes() {
        title = "Student Outcome";
        studentOutcomes = (List<StudentOutcomeClass>) new ArrayList();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        Query studentOutcomesQuery = em.createNamedQuery("Studentoutcome.findAll");
        List<Studentoutcome> soResultList = (List<Studentoutcome>) studentOutcomesQuery.getResultList();

        for (Studentoutcome so : soResultList) {
            if (so.getDegreeprogram() != null) {
                for (Users j : so.getDegreeprogram().getUsersCollection()) {
                    if (j.getUsername().equalsIgnoreCase(userSessionBean.getUsername())) {
                        StudentOutcomeClass soc = new StudentOutcomeClass(so);
                        studentOutcomes.add(soc);
                        soc.setDirectWithQuery(em);
                        soc.setSurveyWithQuery(em);
                    }
                }
            }
        }
        return "ViewStudentOutcomes";
    }

    public String modifySOS() {
        studentOutcomes = (List<StudentOutcomeClass>) new ArrayList();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        Query studentOutcomesQuery = em.createNamedQuery("Studentoutcome.findAll");
        List<Studentoutcome> soResultList = (List<Studentoutcome>) studentOutcomesQuery.getResultList();
        for (Studentoutcome so : soResultList) {
            List<String> path = new ArrayList();
            if (so.getDegreeprogram() != null) {
                path.add(Degreeprogram.class.getSimpleName());
                path.add(Users.class.getSimpleName());
                if (GUIUtilityClass.isUserRole(path, 0, so)) {
                    LOG.info(so.getIdentifier());
                    StudentOutcomeClass soc = new StudentOutcomeClass(so);
                    studentOutcomes.add(soc);
                }
            } else {
                StudentOutcomeClass soc = new StudentOutcomeClass(so);
                studentOutcomes.add(soc);
            }
        }
        return "modifySO";
    }

    public String saveSO() {
        List<GeneralTest> gtList = new ArrayList();
        for (StudentOutcomeClass soc : this.studentOutcomes) {
            gtList.add(soc);
        }
        if (utilities.checkDuplicates(gtList)) {
            FacesMessage message = new FacesMessage();
            message.setDetail(GUIUtilityClass.duplicateWarning);
            FacesContext.getCurrentInstance().addMessage("form", message);
            return "";
        }
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH);
        int cmonth;
        if (month < 6) {
            cmonth = 1;
        } else {
            cmonth = 0;
        }
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        for (int i = 0; i < studentOutcomes.size(); i++) {
            StudentOutcomeClass s1 = studentOutcomes.get(i);
            Studentoutcome s2 = (Studentoutcome)s1.findCorrespondingEntity();
            s2.setIdentifier(s1.getIdentifier());
            s2.setSequencenumber(s1.getSequenceNumber());
            s2.setShortname(s1.getShortName());
            s2.setDescription(s1.getDescription());
            s2.setSemester(cmonth);
            s2.setYea(year);
            em.merge(s2);
        }
        em.getTransaction().commit();
        return null;
    }

    public String createStdOut() {
        return "createStuOut";
    }

    public String createSO() {
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH);
        int cmonth;
        if (month < 6) {
            cmonth = 1;
        } else {
            cmonth = 0;
        }

        Studentoutcome so1 = new Studentoutcome();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();

        so1.setIdentifier(this.identifier);
        so1.setSequencenumber(this.seqNum);
        so1.setShortname(this.shortName);
        so1.setDescription(this.Description);
        if (utilities.checkPK(so1)) {
            FacesMessage message = new FacesMessage();
            message.setDetail(GUIUtilityClass.createWarning);
            FacesContext.getCurrentInstance().addMessage("form", message);
            return "";
        }
        em.persist(so1);

        em.getTransaction().commit();

        return "welcome";
    }

    public UserSessionBean getUserSessionBean() {
        return userSessionBean;
    }

    public void setUserSessionBean(UserSessionBean userSessionBean) {
        this.userSessionBean = userSessionBean;
    }

    public List<StudentOutcomeClass> getStudentOutcomes() {
        return studentOutcomes;
    }

    public void setStudentOutcomes(List<StudentOutcomeClass> studentOutcomes) {
        this.studentOutcomes = studentOutcomes;
    }

    public String getIdentifier() {
        return identifier;
    }

    public void setIdentifier(String identifier) {
        this.identifier = identifier;
    }

    public int getSeqNum() {
        return seqNum;
    }

    public void setSeqNum(int seqNum) {
        this.seqNum = seqNum;
    }

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    public String getDescription() {
        return Description;
    }

    public void setDescription(String Description) {
        this.Description = Description;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void saveCDA(ActionEvent ae) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Integer row = (Integer) ae.getComponent().getNamingContainer().getParent().getParent().getAttributes().get("rowIndex");
        StudentOutcomeClass soc = this.studentOutcomes.get(row);
        Studentoutcome so = (Studentoutcome) soc.findCorrespondingEntity();
        String semester2 = soc.getCurrentSemesterTDAA();
        String semester = "";
        StringTokenizer st = new StringTokenizer(semester2);
        semester += st.nextToken() + " " + st.nextToken();
        int attainment = soc.getCurrentDirectAssessment();
        Collection<Targetdirectassessment> tdac = so.getTargetdirectassessmentCollection();
        for (Targetdirectassessment tda : tdac) {
            if (tda.getTargetdirectassessmentPK().getSemester().equals(semester)) {
                tda.setAttainmentlevel(attainment);
                em.merge(tda);
                em.getTransaction().commit();;
                break;
            }
        }
    }

    public void saveCSA(ActionEvent ae) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Integer row = (Integer) ae.getComponent().getNamingContainer().getParent().getParent().getAttributes().get("rowIndex");
        StudentOutcomeClass soc = this.studentOutcomes.get(row);
        Studentoutcome so = (Studentoutcome) soc.findCorrespondingEntity();
        String semester2 = soc.getCurrentSemesterTSAA();
        String semester = "";
        StringTokenizer st = new StringTokenizer(semester2);
        semester += st.nextToken() + " " + st.nextToken();
        int attainment = soc.getCurrentSurveyAssessment();
        Collection<Targetsurveyassessment> tsal = so.getTargetsurveyassessmentCollection();
        for (Targetsurveyassessment tsa : tsal) {
            if (tsa.getTargetsurveyassessmentPK().getSemester().equals(semester)) {
                tsa.setAttainmentlevel(attainment);
                em.merge(tsa);
                em.getTransaction().commit();
                break;
            }
        }
    }
}